﻿using DevExpress.Utils.Extensions;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraNavBar;
using DevExpress.XtraTab;
using Lamex.Common;
using Lamex.Core;
using Lamex.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace Lamex.Library.CommonClass
{
   public class ModuleManager
    {
        private XtraTabControl _tabControlModules = null;
        public XtraTabControl TabControlModules { get { return _tabControlModules; } }
        private Form _MDIMainForm = null;
        private IList<IModuleBase> _ModuleLoadSucceed = new List<IModuleBase>();
        public IList<IModuleBase> ModuleLoadSucceed { get { return _ModuleLoadSucceed; } }
        private static IList<ModuleInfo> _Modules = null;
        private static IList<ModuleInfo> _tempModules = null;
        public static IList<ModuleInfo> GetAvaiableModules()
        {
            return _Modules;
        }
        public ModuleManager(Form mdiMainForm, XtraTabControl tabControlModules)
        {
            _tabControlModules = tabControlModules;
            _MDIMainForm = mdiMainForm;
        }
        #region "menu"

        string pathServer = AppDomain.CurrentDomain.BaseDirectory;
        Dictionary<string, Assembly> Assemblys = new Dictionary<string, Assembly>();
        Dictionary<string, TypeInfo> TypeInfos = new Dictionary<string, TypeInfo>();
        public void LoadModulesNew(IMsg msg, MenuStrip moduleMenus)
        {
            
            DataRow[] drList = SystemAuthentication.UserMenu.Select("PID='-1'").OrderBy(x => x["SortCode"]).ToArray();
            foreach (DataRow dr in drList)
            {
                var id = dr.Field<string>("Id");
                var name = dr.Field<string>("Name");
                var EngName = dr.Field<string>("EngName");
                //var autoCode = dr.Field<string>("FormAutoCode");

                msg.UpdateMessage("正在加载：" + name);
                //Loginer.CurrentUser.FunctionId = id;

                var item = new ToolStripMenuItem();
                item.Name = id;
                if(Loginer.CurrentUser.ChangeLanguage==0)
                    item.Text = name;
                else
                    item.Text = EngName;
                // item.Tag = autoCode;

                AddModules(item, id);

                moduleMenus.Items.Add(item);
            }
        }

        void AddModules(ToolStripMenuItem parentNode, string parentId)
        {
            string testName = "";
            try
            {
                
                DataRow[] drList = SystemAuthentication.UserMenu.Select(string.Format("PID='{0}'", parentId)).OrderBy(x => x["SortCode"]).ToArray();
                foreach (DataRow dr in drList)
                {
                    var id = dr.Field<string>("id");
                    var name = dr.Field<string>("Name");
                    var winType = dr.Field<string>("WinFormType");
                    var winFormName = dr.Field<string>("WinFormName");
                    var winOpenType = dr.Field<string>("OpenFormType");
                    var EngName = dr.Field<string>("EngName");
                    testName = winType + "+" + winFormName+"+"+ winOpenType;
                    //Loginer.CurrentUser.FunctionId = id;
                    //var autoCode = dr.Field<string>("FormAutoCode");
                    var item = new ToolStripMenuItem();
                    if (Loginer.CurrentUser.ChangeLanguage == 0)
                        item.Text = name;
                    else
                        item.Text = EngName;
                    item.Name = id;
                    //item.Text = name;
                    //item.Tag = autoCode;
                    if (item.Name == "069038C8-94A9-4B9B-BD6B-0DC49EE4C7F9")
                    {
                        string str = "sss";
                    }

                    //测试
                    #region
                    //if (string.IsNullOrWhiteSpace(winFormName))
                    //{
                    //    winFormName = "frmMenu";
                    //    winType = "JKFrameWork.SysManager.dll";
                    //}
                    #endregion

                    var type = LoadAssembly(winFormName, winType);
                    if (winFormName == null || winFormName == "")
                    {

                    }
                    else if (winFormName.Contains("frmBaseChildWinForm"))
                    {

                        string[] strArr = winOpenType.Split(',');
                        if (strArr.Count() == 4)
                        {
                            string tableName = strArr[0].Trim();
                            int m = 0;
                            bool _IsBool1 = false;
                            bool _IsBool2 = false;
                            m = int.Parse(strArr[1].Trim());
                            if (strArr[2].Trim().ToLower() == "true")
                                _IsBool1 = true;
                            if (strArr[3].Trim().ToLower() == "true")
                                _IsBool1 = true;

                            //Form form =;
                            item.Click += delegate (object sender, EventArgs e)
                            {
                                MdiTools.OpenChildWebBrowse(MdiTools.MdiMainForm as IMdiForm, new frmBaseChildWinForm(tableName, m, _IsBool1, _IsBool2), sender as ToolStripMenuItem);
                            };
                        }
                    }
                    else if (winFormName.Contains("OpenChildWebBrowse"))
                    {

                        string[] strArr = winOpenType.Split(',');
                        if (strArr.Count() == 2)
                        {
                            item.Click += delegate (object sender, EventArgs e)
                            {
                                MdiTools.OpenChildWebBrowse(MdiTools.MdiMainForm as IMdiForm, new frmExeForm(strArr[0], strArr[1].Trim()), sender as ToolStripMenuItem);
                            };
                        }
                    }
                    else if (winFormName.Contains("OpenChildForm_Param"))
                    {
                        type = LoadAssembly(winOpenType, winType);
                        string[] strArr = winOpenType.Split(',');

                        item.Click += delegate (object sender, EventArgs e)
                        {
                            object[] parameters = new object[1];
                            parameters[0] = Lamex.Library.CommonClass.BuildSqlHelper.GetProcType();
                            Form form = (Form)type.Assembly.CreateInstance(type.FullName, true, System.Reflection.BindingFlags.Default, null, parameters, null, null);
                            MdiTools.OpenChildForm_Param(MdiTools.MdiMainForm as IMdiForm, form, id);
                        };

                    }
                    else if (winFormName.Contains("OpenMultiParamForm"))
                    {
                        string[] strArrSplit = winOpenType.Split(':');
                        type = LoadAssembly(strArrSplit[0], winType);
                        string[] strArr = strArrSplit[1].Split(',');
                        if (strArr.Length != 0)
                        {
                            item.Click += delegate (object sender, EventArgs e)
                            {
                                object[] parameters = new object[strArr.Length];
                                int m = 0;
                                foreach (string s in strArr)
                                {
                                    if (!string.IsNullOrEmpty(s))
                                    {

                                        parameters[m] = s;
                                        m++;
                                    }
                                }
                                Form form = (Form)type.Assembly.CreateInstance(type.FullName, true, System.Reflection.BindingFlags.Default, null, parameters, null, null);
                                MdiTools.OpenChildForm_Param(MdiTools.MdiMainForm as IMdiForm, form, id);
                            };
                        }
                    }

                    else if (winFormName.Contains("Help"))
                    {
                        string[] strArr = winOpenType.Split(',');

                        item.Click += delegate (object sender, EventArgs e)
                        {
                            Help.ShowHelp(new frmBaseChild(), strArr[0].Trim());
                        };
                    }
                    else if (winFormName.Contains("OpenWebForm"))
                    {

                        string[] strArr = winOpenType.Split(',');
                        if (strArr.Count() == 2)
                        {
                            item.Click += delegate (object sender, EventArgs e)
                            {
                                MdiTools.OpenChildWebBrowse(MdiTools.MdiMainForm as IMdiForm, new frmWebForm(strArr[0], strArr[1].Trim()), sender as ToolStripMenuItem);
                            };
                        }
                    }
                    else if (winFormName.Contains("OpenSingleForm"))
                    {

                        item.Click += delegate (object sender, EventArgs e)
                        {
                            type = LoadAssembly(winOpenType, winType);
                            Form form = (Form)type.Assembly.CreateInstance(type.FullName);
                            form.ShowDialog();
                        };
                    }
                    else if (winFormName.Contains("OpensSingleFormExe"))
                    {
                        string[] strArr = winOpenType.Split(',');
                        if (strArr.Count() == 1)
                        {

                            item.Click += delegate (object sender, EventArgs e)
                            {
                                string exepath = strArr[0];
                                ProcessStartInfo psi = new ProcessStartInfo();
                                psi.FileName = exepath;
                                psi.UseShellExecute = false;
                                psi.CreateNoWindow = true;
                                Process.Start(psi); ;
                            };
                        }
                    }
                    else if (type != null)
                    {
                        item.Click += delegate (object sender, EventArgs e)
                        {

                            MdiTools.OpenChildForm(MdiTools.MdiMainForm as IMdiForm, type.AsType(), sender as ToolStripMenuItem);
                        };

                    }


                    //AddModules(item, id);

                    parentNode.DropDownItems.Add(item);
                    AddModules(item, id);
                }
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message+ parentId+"error name:"+ testName);
            }
        }

        TypeInfo LoadAssembly(string typeName, string assemblyName)
        {
            var typeInfos = TypeInfos;
            var assemblys = Assemblys;
            if (typeName is null)
                return null;
            if (typeInfos.ContainsKey(typeName))
            {
                return typeInfos[typeName];
            }
            Assembly asm;
            //通过保存的方件名取出集合
            if (!string.IsNullOrWhiteSpace(assemblyName))
            {
                try
                {
                    var path = string.Format("{0}{1}", pathServer, assemblyName);
                    asm = Assembly.LoadFile(path);
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                asm = Assembly.GetEntryAssembly();
            }

            if (!assemblys.ContainsKey(assemblyName))
            {
                assemblys[assemblyName] = asm;
            }

            foreach (var type in asm.DefinedTypes)
            {
                typeInfos[type.Name] = type;
            }

            return typeInfos.ContainsKey(typeName) ? typeInfos[typeName] : null;

        }
        #endregion
        public void LoadModules(IMsg msg, MenuStrip moduleMenus)
        {
            MenuStrip Menus = new MenuStrip();
            
            ModuleLoadDevComponent loader = new ModuleLoadDevComponent();
            try
            {
                _Modules = loader.GetModuleList();

                foreach (ModuleInfo m in _Modules)
                {
                    if (!loader.LoadModule(m)) continue;
                    if (!loader.CanAccessModule(SystemAuthentication.UserAuthorities))
                    {
                        loader.ClearAssemble();
                        continue;

                    }

                    _ModuleLoadSucceed.Add(loader.ModuleMainForm);

                    msg.UpdateMessage("正在加载：" + loader.GetCurrentModuleName());
                    loader.LoadMenu(Menus);
                    (loader.ModuleMainForm as Form).MdiParent = _MDIMainForm;

                }

                #region""
                SystemAuthentication.UserMenu.Columns.Add("inserted",typeof(int));
                foreach(DataRow row in SystemAuthentication.UserMenu.Rows)
                {
                    row["inserted"] = 0;
                }
                DataRow[] drList = SystemAuthentication.UserMenu.Select("PID='-1'").OrderBy(x=>x["SortCode"]).ToArray();
                //dataRow dr =OrderByDescending(x=>x["name"]).
                if (drList.Count() > 0)
                {
                    foreach (DataRow dr in drList)
                    {
                        MenuStrip _Menuss = new MenuStrip();
                        ToolStripMenuItem item = new ToolStripMenuItem();
                        for (int n = 0; n < Menus.Items.Count; n++)
                        {
                            ToolStripMenuItem items = Menus.Items[n] as ToolStripMenuItem;
                            //for (int i = 0; i < items.DropDownItems.Count; i++)
                            //{
                            if (items.Name == dr["WinformId"].ToString())
                                {
                                    //ToolStripMenuItem dropItem = items.DropDownItems[i] as ToolStripMenuItem;
                                    item.Name = dr["WinformId"].ToString();
                                    item.Text = dr["Name"].ToString();
                                    
                                    //item.DropDownItems.Add(dropItem);
                                    LoadList(Menus, dr, item);

                                    _Menuss.Items.Add(item);
                                    if ((_Menuss == null) || (_Menuss.Items.Count == 0)) return;
                                    while (_Menuss.Items.Count > 0)
                                    {
                                        int startIndex = moduleMenus.Items.Count == 0 ? 0 : moduleMenus.Items.Count;
                                        moduleMenus.Items.Insert(startIndex, _Menuss.Items[0]);
                                    }

                                }
                            //}
                        }
                        
                    }



                }
            }
            catch (Exception ex)
            {
                MsgShow.ShowException(ex);

            }
                #endregion
                //    #region "old"
                //    MenuStrip _Menus = new MenuStrip();
                //    foreach (ModuleInfo m in _Modules)
                //    {

                //        string name = Path.GetFileName(m.ModuleFile);
                //        DataRow dr = SystemAuthentication.UserMenu.Select("WinformId='" + name + "'").FirstOrDefault();
                //        if (dr!=null)
                //        {
                //            ToolStripMenuItem item = new ToolStripMenuItem();
                //            item.Name = dr["WinformId"].ToString();
                //            item.Text = dr["Name"].ToString();
                //            DataRow[] rows = SystemAuthentication.UserMenu.Select("PID='" + dr["ID"].ToString() + "'");
                //            if (rows.Count() > 0)
                //            {
                //                for (int n = 0; n < Menus.Items.Count; n++)//二级菜权限控制
                //                {
                //                    ToolStripMenuItem Items = Menus.Items[n] as ToolStripMenuItem;
                //                    LoadItem(Menus,Items, rows, item);

                //                }
                //            }
                //            //foreach(DataRow drow in rows)
                //            //{
                //            //    if (drow!=null)
                //            //    {
                //                    //for (int n = 0; n < Menus.Items.Count; n++)//二级菜权限控制
                //                    //{
                //                    //    ToolStripMenuItem Items = Menus.Items[n] as ToolStripMenuItem;
                //                    //    ToolStripDropDownItem dropItems = null;
                //                    //    foreach (DataRow drow in rows)
                //                    //    {
                //                    //        for (int i = 0; i < Items.DropDownItems.Count; i++)
                //                    //        {
                //                    //            dropItems = new ToolStripMenuItem();
                //                    //            dropItems = Items.DropDownItems[i] as ToolStripDropDownItem;
                //                    //            string na = dropItems.Name;

                //                    //            if (dropItems.Name == drow["WinformId"].ToString())
                //                    //            {
                //                    //                item.DropDownItems.Add(dropItems);//2018-11-13
                //                    //                //item.DropDownItems[1]
                //                    //                //ToolStripDropDownItem downitem = item.DropDownItems[i];
                //                    //                //LoadItem(dropItems, item.DropDownItems);
                //                    //            }
                //                    //        }
                //                    //    }
                //                    //}
                //            _Menus.Items.Add(item);
                //            //_Menus.Items.Add(item);
                //        }

                //        if ((_Menus == null) || (_Menus.Items.Count == 0)) return;
                //        while (_Menus.Items.Count > 0)//加载所有顶级菜单
                //        {
                //            int startIndex = moduleMenus.Items.Count == 0 ? 0 : moduleMenus.Items.Count;
                //            moduleMenus.Items.Insert(startIndex, _Menus.Items[0]);

                //        }

                //    }
                //    //(loader.ModuleMainForm as Form).MdiParent = _MDIMainForm;
                //    GC.Collect();
            //}
            //catch (Exception ex)
            //{
            //    MsgShow.ShowException(ex);

            //}
                //    #endregion
           
        }
        private void LoadList(MenuStrip Menus, DataRow row, ToolStripMenuItem item)
       {
           DataRow[] drList = SystemAuthentication.UserMenu.Select("PID='" + row["ID"].ToString() + "' and inserted=0 ").OrderBy(x => x["SortCode"]).ToArray();//开始加载次级菜单
           if (drList.Count()>0)
           {
               foreach(DataRow dr in drList)
               {
                   int m=0;
                   ToolStripDropDownItem dropItem=null;
                   //for (int n = 0; n < Menus.Items.Count; n++)//
                   //{
                   //    //ToolStripMenuItem items = Menus.Items[n] as ToolStripMenuItem;
                   //    //for (int i = 0; i < items.DropDownItems.Count; i++)
                   //    //{
                   //    //    if (items.DropDownItems[i].Name == dr["WinformId"].ToString())
                   //    //    {
                   //    //        dropItem = items.DropDownItems[i] as ToolStripDropDownItem;
                   //    //        m=1;
                   //    //    }
                   //    //}

                       
                   //}
                   
                   foreach(ToolStripMenuItem items in Menus.Items)
                   {
                       if (dropItem==null)
                           EnumEachItem(items, ref dropItem, dr);
                   }
                   if (dropItem != null)
                   {
                       m = 1;
                   }
                   //加载
                   if (m == 1)
                   {
                       DataRow[] List = SystemAuthentication.UserMenu.Select("PID='" + dr["ID"].ToString() + "' and inserted=0 ").OrderBy(x => x["SortCode"]).ToArray();//开始加载次级菜单
                       if (List.Count() > 0)
                       {
                           //ToolStripMenuItem newMenu = dropItem as ToolStripMenuItem;
                           ToolStripMenuItem newMenu = new  ToolStripMenuItem();
                           newMenu.Name = dropItem.Name;
                           newMenu.Text = dropItem.Text;
                           
                           item.DropDownItems.Add(newMenu);
                           LoadList(Menus, dr, newMenu);
                       }
                       else
                       {
                            DataRow hasedRow = SystemAuthentication.UserMenu.Select("ID='" + dr["ID"].ToString() + "'").FirstOrDefault();
                            hasedRow["inserted"] = 1;
                            dropItem.Text = dr["Name"].ToString();
                            item.CheckState = CheckState.Checked;
                            item.DropDownItems.Add(dropItem);
                       }
                       
                   }
                   else
                   {
                       DataRow[] List = SystemAuthentication.UserMenu.Select("PID='" + dr["ID"].ToString() + "' and inserted=0").OrderBy(x => x["SortCode"]).ToArray();//开始加载次级菜单
                       if (List.Count()>0)
                       {
                           ToolStripMenuItem newMenu = new ToolStripMenuItem();
                           newMenu.Name = dr["WinformId"].ToString();
                           newMenu.Text = dr["Name"].ToString();
                            DataRow hasedRow = SystemAuthentication.UserMenu.Select("ID='" + dr["ID"].ToString() + "'").FirstOrDefault();
                            hasedRow["inserted"] = 1;
                            item.CheckState = CheckState.Checked;
                            item.DropDownItems.Add(newMenu);
                           LoadList(Menus, dr, newMenu);
                       }
                       //else
                       //{
                       //    ToolStripMenuItem newMenu = new ToolStripMenuItem();
                       //    newMenu.Name = dr["WinformId"].ToString();
                       //    newMenu.Text = dr["Name"].ToString();
                       //    item.DropDownItems.Add(newMenu);
                       //}
                       
                   }
                   m = 0;
               }
           }
           //for (int n = 0; n < Menus.Items.Count; n++)//二级菜权限控制
           //{
           //    ToolStripMenuItem items=Menus.Items[n] as ToolStripMenuItem;
           //    ToolStripMenuItem dropItems = new ToolStripMenuItem();
           //    for (int i = 0; i < items.DropDownItems.Count; i++)
           //    {
           //        if (items.DropDownItems[i].Name == row["WinformId"].ToString())
           //        {
           //            ToolStripDropDownItem dropItem = items.DropDownItems[i] as ToolStripDropDownItem;
           //            item.DropDownItems.Add(dropItem);
           //            DataRow[] drList = SystemAuthentication.UserMenu.Select("PID='" + row["ID"].ToString() + "'");//开始加载次级菜单
           //            foreach(DataRow sub in drList)
           //            {
           //                if (drList.Count() > 0)
           //                {
           //                    ToolStripMenuItem newMenu = items.DropDownItems[i] as ToolStripMenuItem;
           //                    newMenu.Enabled = true;
           //                    newMenu.Visible = true;
           //                    ToolStripMenuItem test = new ToolStripMenuItem();
           //                    item.DropDownItems.Add(newMenu);

           //                }
           //                else
           //                {
           //                    item.DropDownItems.Add(dropItem);//2018-11-13
           //                }
           //            }
                       

                           
                   
           //    }
           //}
           
           //}

       }
        private void EnumEachItem(ToolStripMenuItem item, ref  ToolStripDropDownItem dropItem, DataRow dr)
       {
          
           for (int i = 0; i < item.DropDownItems.Count; i++)
           {
                //if (item.CheckState == CheckState.Checked) continue;
                if (item.DropDownItems[i].Name == dr["WinformId"].ToString())
               {
                    DataRow hasedRow = SystemAuthentication.UserMenu.Select("ID='" + dr["ID"].ToString() + "'").FirstOrDefault();
                    hasedRow["inserted"] = 1;
                    dropItem = item.DropDownItems[i] as ToolStripDropDownItem;
                   dropItem.Text = dr["Name"].ToString();
                    item.CheckState = CheckState.Checked;
                   break;
                   
               }
               ToolStripMenuItem subitem = item.DropDownItems[i] as ToolStripMenuItem;
                subitem.Text = dr["Name"].ToString();
                //if (item.CheckState == CheckState.Checked) continue;
                EnumEachItem(subitem, ref dropItem, dr);
           }
           //foreach (ToolStripMenuItem sub in item.DropDownItems)
           // {
           //     ToolStripDropDownItem newMenu = sub as ToolStripDropDownItem;
           //     if (newMenu.Name == dr["WinformId"].ToString())
           //     {
           //         dropItem = newMenu;
           //         break;
           //     }
           //     EnumEachItem(sub, ref dropItem,dr);
           // }
           
       }
       /// <summary>
       /// 加载多菜单
       /// </summary>
        private void LoadItem(MenuStrip Menu, ToolStripMenuItem Menus, DataRow[] rows, ToolStripMenuItem item)
        {

            for (int n = 0; n < Menu.Items.Count; n++)
            {
            ToolStripMenuItem Items = Menu.Items[n] as ToolStripMenuItem;
            ToolStripMenuItem dropItems = new ToolStripMenuItem();

            //ToolStripMenuItem Items = Menus.Items[n] as ToolStripMenuItem;
            //ToolStripDropDownItem dropItems = null;
                foreach (DataRow drow in rows)
                {
                    
                    for (int i = 0; i < Items.DropDownItems.Count; i++)
                    {
                        //dropItems = new ToolStripMenuItem();
                        //dropItems = Items.DropDownItems[i] as ToolStripDropDownItem;
                        //string na = dropItems.Name;

                        if (Items.DropDownItems[i].Name == drow["WinformId"].ToString())
                        {
                            
                            //dropItems.DropDownItems.Add(Items.DropDownItems[i]);
                            ToolStripDropDownItem dropItem = Items.DropDownItems[i] as ToolStripDropDownItem;
                            //item.DropDownItems.Add(Items.DropDownItems[i]);//2018-11-13
                            //dropItems.DropDownItems.Add(Items.DropDownItems[i]);
                            //if(Items.DropDownItems[i].Name!=item.Name)
                            //int m = item.DropDownItems.Count - 1;
                            
                            DataRow []  drows = SystemAuthentication.UserMenu.Select("PID='" + drow["ID"].ToString() + "'");
              

                            if (drows.Count() > 0) 
                            {
                                //ToolStripMenuItem dropMenu = item.DropDownItems[m] as ToolStripMenuItem;
                                ////dropItems as ToolStripMenuItem;
                                //ToolStripMenuItem newStrip = Items.DropDownItems[i] as ToolStripMenuItem;
                                //dropItems.DropDownItems.Add(Items.DropDownItems[i]);
                                ToolStripMenuItem newMenu = Items.DropDownItems[i] as ToolStripMenuItem;
                                newMenu.Enabled = true;
                                newMenu.Visible = true;

                                ToolStripMenuItem test = new ToolStripMenuItem();
                                
                                //ToolStripMenuItem it = newMenu;
                                //newMenu.DropDownItems.Add("123");
                                //newMenu.DropDownItems.Add("1234");
                                //newMenu.Enabled = true;
                                //newMenu.DropDownItems.Add(dropItem);
                                //newMenu.
                                ////newMenu.DropDownItems.Add(dropItem);
                                //newMenu.DropDownItems.Add("123");

                                item.DropDownItems.Add(newMenu);
                                //item.DropDownItems.Add(newMenu);
                                //LoadItem(Items, drows, item);
                                ////ToolStripMenuItem sitemt = new ToolStripMenuItem();
                                ////sitemt.Text = "sdf";
                                ////sitemt.Name = "as35";
                                ////newMenu.DropDownItems.Add(sitemt);
                                //LoadItem(Items, drows, newMenu);
                            }
                            else
                            {
                                item.DropDownItems.Add(dropItem);//2018-11-13
                            }

                            //item.DropDownItems[1]
                            //ToolStripDropDownItem downitem = item.DropDownItems[i];
                            //LoadItem(dropItems, item.DropDownItems);
                        }
                        
                    }
                }
            }
                
        }
        private void LoadsuItem(ToolStripMenuItem Menus, DataRow[] rows, ToolStripMenuItem item)
        {
            ToolStripMenuItem Items = Menus as ToolStripMenuItem;
            foreach (DataRow drow in rows)
            {

                for (int i = 0; i < Items.DropDownItems.Count; i++)
                {
                    //dropItems = new ToolStripMenuItem();
                    //dropItems = Items.DropDownItems[i] as ToolStripDropDownItem;
                    //string na = dropItems.Name;

                    if (Items.DropDownItems[i].Name == drow["WinformId"].ToString())
                    {
                        ToolStripDropDownItem dropItem = Items.DropDownItems[i] as ToolStripDropDownItem;
                        DataRow[] drows = SystemAuthentication.UserMenu.Select("PID='" + drow["ID"].ToString() + "'");
                        if (drows.Count() > 0)
                        {
                           
                            //ToolStripMenuItem newMenu = Items.DropDownItems[i] as ToolStripMenuItem;
                            //item.DropDownItems.Add(newMenu);
                            //LoadsuItem(Items, drows, newMenu);
                        }
                        else
                        {
                            dropItem.Enabled = true;
                            dropItem.Visible = true;
                            item.DropDownItems.Add(dropItem);//2018-11-13
                            item.Enabled = true;
                            item.Visible = true;
                        }

                        //item.DropDownItems[1]
                        //ToolStripDropDownItem downitem = item.DropDownItems[i];
                        //LoadItem(dropItems, item.DropDownItems);
                    }

                }
                //}
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="menuStrip"></param>
        public void SetModuleSecurity(MenuStrip menuStrip)
        {
            try
            {
                foreach (XtraTabPage page in this._tabControlModules.TabPages)
                {
                    Form activeForm = (Form)page.Tag;
                    if (null != activeForm)
                        (activeForm as IModuleBase).SetSecurity(menuStrip);
                }
            }
            catch (Exception ex) { MsgShow.ShowException(ex); }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="menuBar"></param>
        /// <param name="mainMenu"></param>
        public void CreateToolButtons(Bar menuBar, ToolStrip moduleMainMenu)
        {
            foreach (ToolStripMenuItem moduleTopMenu in moduleMainMenu.Items)
            {
                //if (!moduleTopMenu.Enabled) continue;
                moduleTopMenu.Enabled = true;//2018-11-14

                BarSubItem menuOwner = new BarSubItem(menuBar.Manager, moduleTopMenu.Text);
                menuOwner.AllowDrawArrow = DevExpress.Utils.DefaultBoolean.False;
                // menuOwner.PaintStyle = BarItemPaintStyle.CaptionGlyph;
                //menuOwner.Glyph = moduleTopMenu.Image;
                menuOwner.Tag = moduleTopMenu;
                menuOwner.Name = moduleTopMenu.Name;
                menuOwner.ItemClick += new ItemClickEventHandler(menuOwner_ItemClick);
                menuOwner.Enabled = true;
                
                menuBar.ItemLinks.Add(menuOwner);


                //递归加载
                foreach (ToolStripItem item in moduleTopMenu.DropDownItems)
                {
                    if (item is ToolStripSeparator) continue;
                    item.Enabled = true;
                    if (!item.Enabled) continue;
                    item.Enabled = true;//2018-11-14
                    if (item is ToolStripMenuItem && (item as ToolStripMenuItem).DropDownItems.Count > 0)
                    {

                        BarSubItem itemOwner = new BarSubItem(menuBar.Manager, item.Text);
                        itemOwner.Name = item.Name;

                        menuOwner.ItemLinks.Add(itemOwner);
                        itemOwner.Enabled = true;//2018-11-14
                        this.LoadBarSubItems(itemOwner, item as ToolStripMenuItem);
                    }
                    else
                    {
                        menuOwner.Enabled = true;//2018-11-14
                        this.LoadBarButtonItem(menuOwner, item);
                    }
                }
            }
        }

        
        void menuOwner_ItemClick(object sender, ItemClickEventArgs e)
        {
            if ((e.Item.Tag != null) && (e.Item.Tag is ToolStripItem))
                (e.Item.Tag as ToolStripItem).PerformClick();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="item"></param>
        private void LoadBarButtonItem(BarSubItem owner, ToolStripItem item)
        {
            BarButtonItem button = new BarButtonItem();
            button.Caption = item.Text;
            button.Tag = item;
            button.Name = item.Name;
            button.ItemClick += new ItemClickEventHandler(OnBarButtonItemClick);
            owner.ItemLinks.Add(button);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBarButtonItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.Item.Tag != null && e.Item.Tag is ToolStripItem)
                (e.Item.Tag as ToolStripItem).PerformClick();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="itemOwner"></param>
        /// <param name="menuItem"></param>
        private void LoadBarSubItems(BarSubItem itemOwner, ToolStripMenuItem menuItem)
        {
            foreach (ToolStripItem item in menuItem.DropDownItems)
            {
                if (item is ToolStripSeparator) continue;
                //if (!item.Enabled) continue; //菜单是禁止使用状态，无权限2018-11-14
                item.Enabled = true;
                if (item is ToolStripMenuItem && (item as ToolStripMenuItem).DropDownItems.Count > 0)
                {
                    BarSubItem subItem = new BarSubItem(itemOwner.Manager, item.Text);
                    itemOwner.ItemLinks.Add(subItem);
                    this.LoadBarSubItems(subItem, item as ToolStripMenuItem);
                }
                else
                {
                    this.LoadBarButtonItem(itemOwner, item);
                }
            }
        }

        /// <summary>
        /// 跟据菜单创建导航组件
        /// </summary>
        /// <param name="navBarControl">导航控件</param>
        /// <param name="mainMenu">主菜单</param>
        /// <param name="style">导航控件的自定义显示类型</param>
        //public void CreateNavBarButtons(NavBarControl navBarControl, MenuStrip mainMenu, NavigatorStyle style)
        public void CreateNavBarButtons(NavBarControl navBarControl, MenuStrip mainMenu)
        {
            
            NavigatorBase creator;

            
            //if (NavigatorStyle.BarItem == style)
            //    creator = new NavigatorBarList(this);
            //else
                creator = new NavigatorTreeView(this);

            navBarControl.BeginUpdate();
            creator.CreateNavigator(mainMenu, navBarControl);
            navBarControl.EndUpdate();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="moduleDisplayName"></param>
        public void ActiveModule(string moduleDisplayName)
        {
            //
            (_MDIMainForm as IMdiForm).ShowModuleContainerForm();

            //
            foreach (XtraTabPage page in this._tabControlModules.TabPages)
            {
                if (page.Text.Equals(moduleDisplayName))
                {
                    _tabControlModules.SelectedTabPage = page;
                    _tabControlModules.HeaderLocation = DevExpress.XtraTab.TabHeaderLocation.Bottom;
                }


            }
        }

        public void ChangeEngLanguages(Bar barTools, MenuStrip _moduleMenus, NavBarControl navBarControl)
        {

            //Bar tempBar = new Bar() ;
            //BarManager manager = new BarManager();
            //tempBar.Manager = barTools.Manager;

            //foreach (DevExpress.XtraBars.BarItem sub in barTools.Manager.Items)
            //{
            //    BarSubItem itemOwner = new BarSubItem();
            //    itemOwner.Name = sub.Name;
            //    tempBar.Manager.Items.Add(itemOwner);
            //}

            //int iTems = barTools.Manager.Items.Count;
            _moduleMenus.Items.Clear();
            DataTable dt = SystemAuthentication.UserMenu;
            foreach(DataRow dr in dt.Rows)
            {
                foreach (DevExpress.XtraBars.BarItem sub in barTools.Manager.Items)
                {
                    if(dr["id"].ToString()==sub.Name)
                    {
                        barTools.Manager.Items.Remove(sub);
                        break;
                    }
                }
             }
            Label lblStatus = new Label();
            
            LoadModulesNew(new LoadStatus(lblStatus), _moduleMenus);
            CreateToolButtons(barTools, _moduleMenus);
            //foreach (DevExpress.XtraBars.BarItem sub in barTools.Manager.Items)
            //{
            //    //string it = "BD14758A-419F-4953-A780-CA11B51789D6";
            //    //BarItem item = null;
            //    //item = sub;
            //    //if (sub.Name == it)
            //    //{
            //    //    int len = it.Length;
            //    //}
            //    //if (sub.Name.Length == 36)
            //    //{
            //    //    //barTools.Manager.Items.Remove();
            //    //}

            //}

            //int iTems = barTools.Manager.Items.Count;
            //for (int i = 0; i < iTems; i++)
            //{
            //    int id = (barTools.Manager.Items[i] as BarItem).Name.Length;
            //    if (id == 36)
            //    {
            //        barTools.Manager.Items.Remove((barTools.Manager.Items[i] as BarItem));
            //        iTems--;
            //        i++;

            //    }

            //}
            //for (int i = 0; i < m; i++)
            //{
            //    if (_moduleMenus.Items[0].Name.Length == 36)
            //    {
            //        _moduleMenus.Items.RemoveAt(0);

            //        //BarSubItem[] sub = 
            //        //barTools.RemoveLink()
            //    }
            //}
            //foreach (ToolStripMenuItem item in _moduleMenus.Items)
            //{
            //    ChangeEngLanguage(item);
            //}
            //foreach (DevExpress.XtraBars.BarItem sub in barTools.Manager.Items)
            //{
            //    if(sub!=null)
            //    {
            //        if (sub.Name.Length != 36) continue;
            //        DataRow drow = SystemAuthentication.UserMenu.Select("ID='" + sub.Name + "'").FirstOrDefault();
            //        if (sub.Name == drow["id"].ToString())
            //        {
            //            sub.Caption = drow["EngName"].ToString();
            //        }
            //    }
                
            //    //ToolStripMenuItem subitem = sub.Tag as ToolStripMenuItem;
            //    //if (sub != null)
            //    //{
            //    //    DataRow dr = SystemAuthentication.UserMenu.Select("ID='" + sub.Name + "'").FirstOrDefault();

            //    //    if (dr != null)
            //    //    {
            //    //        //subitem.Text = dr["EngName"].ToString();
            //    //        sub.Caption = dr["EngName"].ToString();
            //    //        DataRow[] drs = SystemAuthentication.UserAuthorities.Select(" PID='" + dr["ID"] + "'");
            //    //        //if (sub.Name == "13807C22-A1A6-4B15-BF13-8F2A31CCB44B")
            //    //        //{
            //    //        //    sub.Caption = "123";
            //    //        //}
            //    //        //if(dr["EngName"].ToString()=="Part Size")
            //    //        //{
            //    //        //    string str = "";
            //    //        //}

            //    //        if (drs.Count() != 0)
            //    //        {
            //    //            foreach (DataRow d in drs)
            //    //            {
            //    //                foreach (DevExpress.XtraBars.BarItem b in barTools.Manager.Items)
            //    //                {
            //    //                    if (b.Name == null) continue;
            //    //                    if (b.Name.ToString() == d["ID"].ToString())
            //    //                    {
            //    //                        sub.Caption = "123";
            //    //                        DataRow drow = SystemAuthentication.UserMenu.Select("ID='" + b.Name + "'").FirstOrDefault();
            //    //                        b.Caption = drow["EngName"].ToString();
            //    //                    }
            //    //                }
            //    //            }

            //    //        }

            //    //    }
            //    //}
            //}
        }
        private void ChangeEngLanguage(ToolStripMenuItem item)
        {
            
            DataRow dr = SystemAuthentication.UserMenu.Select("ID='" + item.Name + "'").FirstOrDefault();
            if (dr != null)
                item.Text = dr["EngName"].ToString();
            foreach (ToolStripMenuItem c in item.DropDownItems)
            {
                c.Enabled = true;
                //ToolStripMenuItem dropItem = c as ToolStripMenuItem;
                
                //ToolStripItem dropItema = c as ToolStripItem;
                
                DataRow _dr = SystemAuthentication.UserMenu.Select("ID='" + c.Name + "'").FirstOrDefault();
                //if (_dr != null)
                //{
                //    dropItema.Text = _dr["EngName"].ToString();//修改
                //    dropItem.Text = _dr["EngName"].ToString();//修改
                //    c.Text = _dr["EngName"].ToString();//修改
                //}
                
                ChangeEngLanguage(c);
            }
            
            //DataRow dr = SystemAuthentication.UserMenu.Select("WinformId='" + item.Name + "'").FirstOrDefault();
            //if (dr != null)
            //    item.Text = dr["EngName"].ToString();
            //foreach (ToolStripDropDownItem c in item.DropDownItems)
            //{
            //    ToolStripMenuItem dropItem = c as ToolStripMenuItem;
            //    ToolStripItem dropItema = c as ToolStripItem;
            //    DataRow _dr = SystemAuthentication.UserMenu.Select("WinformId='" + dropItema.Name + "'").FirstOrDefault();
            //    if (_dr != null)
            //        dropItem.Text = _dr["EngName"].ToString();
            //    ChangeEngLanguage(dropItem);
            //}
        }

        public void ChangeChLanguages(Bar barTools, MenuStrip _moduleMenus, NavBarControl navBarControl)
        {
            _moduleMenus.Items.Clear();
            DataTable dt = SystemAuthentication.UserMenu;
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DevExpress.XtraBars.BarItem sub in barTools.Manager.Items)
                {
                    if (dr["id"].ToString() == sub.Name)
                    {
                        barTools.Manager.Items.Remove(sub);
                        break;
                    }
                }
            }
            Label lblStatus = new Label();
            LoadModulesNew(new LoadStatus(lblStatus), _moduleMenus);
            CreateToolButtons(barTools, _moduleMenus);

            //foreach (ToolStripMenuItem item in _moduleMenus.Items)
            //{


            //    ChangeChLanguage(item);
            //}
            //foreach (DevExpress.XtraBars.BarItem sub in barTools.Manager.Items)
            //{
            //    if (sub != null)
            //    {
            //        if (sub.Name.Length != 36) continue;
            //        DataRow drow = SystemAuthentication.UserMenu.Select("ID='" + sub.Name + "'").FirstOrDefault();
            //        if (sub.Name == drow["id"].ToString())
            //        {

            //            sub.Caption = drow["Name"].ToString();
            //        }
            //    }
            //    //ToolStripMenuItem subitem = sub.Tag as ToolStripMenuItem;
            //    //if (sub != null)
            //    //{

            //    //    DataRow dr = SystemAuthentication.UserMenu.Select("ID='" + sub.Name + "'").FirstOrDefault();
            //    //    //if (dr["Name"].ToString() == "寸尺参数")
            //    //    //{
            //    //    //    string str = "";
            //    //    //}
            //    //    if (dr != null)
            //    //    {
            //    //        //subitem.Text = dr["Name"].ToString();
            //    //        sub.Caption = dr["Name"].ToString();
            //    //        DataRow[] drs = SystemAuthentication.UserAuthorities.Select(" PID='" + dr["ID"] + "'");
            //    //        //if (sub.Name == "13807C22-A1A6-4B15-BF13-8F2A31CCB44B")
            //    //        //{
            //    //        //    sub.Caption = "123";
            //    //        //}
            //    //        if (drs.Count() != 0)
            //    //        {
            //    //            foreach (DataRow d in drs)
            //    //            {
            //    //                foreach (DevExpress.XtraBars.BarItem b in barTools.Manager.Items)
            //    //                {

            //    //                    // b.Caption = "123";
            //    //                    if (b.Name == d["id"].ToString())
            //    //                    {
            //    //                        DataRow drow = SystemAuthentication.UserMenu.Select("ID='" + b.Name + "'").FirstOrDefault();
            //    //                        b.Caption = drow["Name"].ToString();
            //    //                    }
            //    //                }

            //    //            }

            //    //        }
            //    //    }
            //    //}
            //}
        }
        private void ChangeChLanguage(ToolStripMenuItem item)
        {
            if (item.Name == "13807C22-A1A6-4B15-BF13-8F2A31CCB44B")
            {
                string str = "sss";
            }
            DataRow dr = SystemAuthentication.UserMenu.Select("ID='" + item.Name + "'").FirstOrDefault();
            if(item.Name== "13807C22-A1A6-4B15-BF13-8F2A31CCB44B")
            {
                string str = "";
            }
            if (item.Name == "8526048F-12B7-4DFE-91DD-5F232AB39F0C")
            {
                string str = "";
            }
            if (dr != null)
                item.Text = dr["Name"].ToString();
            foreach (ToolStripDropDownItem c in item.DropDownItems) 
            {
                c.Enabled = true;
               
                ToolStripMenuItem dropItem = c as ToolStripMenuItem;
                dropItem.Enabled = true;
                
                ToolStripItem dropItema = c as ToolStripItem;
                DataRow _dr = SystemAuthentication.UserMenu.Select("ID='" + dropItem.Name + "'").FirstOrDefault();
                if (_dr != null)
                {
                    dropItema.Text = _dr["Name"].ToString();//修改
                    dropItem.Text = _dr["Name"].ToString();//修改
                    c.Text = _dr["EngName"].ToString();//修改
                }
                //dropItem.Text = "125";
                //c.Text = "123";
                    ChangeChLanguage(dropItem);
            }
        }
    }
}
